//
//  ChatMessageViewController.m
//  MyChat
//
//  Created by Ansen on 15-2-5.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "ChatMessageViewController.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#import "LoginUser.h"
#import "NSString+Helper.h"
#import "ChatMessageCell.h"

@interface ChatMessageViewController ()<UITextFieldDelegate,NSFetchedResultsControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSFetchedResultsController *_fetchedResultsController;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstant;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ChatMessageViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
     
//    if (IOS7) {
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//    }
    
    // 1. 利用通知中心监听键盘的变化（打开、关闭、中英文切换）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    // 2. 初始化查询结果控制器
    [self setupFetchedResultsController];
    
}

-(void)setupFetchedResultsController
{
    // 1. 实例化数据存储上下文
    NSManagedObjectContext *context = [[APP_DELEGATE xmppMessageArchivingCoreDataStorage] mainThreadManagedObjectContext];
    
    // 2. 定义查询请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    
     // 3. 定义排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    [request setSortDescriptors:@[sort]];
    
    // 4. 定义查询条件(谓词，NSPredicate)
    // 查询来自与hello发给admin的消息
    request.predicate = [NSPredicate predicateWithFormat:@"bareJidStr CONTAINS[cd] %@ AND streamBareJidStr CONTAINS[cd] %@",_bareJidStr,Login_User.myJIDName];
    
    // 5. 实例化查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    
    // 6. 设置代理
    _fetchedResultsController.delegate = self;
    
    // 7. 执行查询
    NSError *error;
    if (![_fetchedResultsController performFetch:&error]) {
        NSLog(@"查询数据出错 - %@", error.localizedDescription);
    }else{
//          _bottomConstant.constant = 100;
//         [self.view layoutIfNeeded];
        [self scrollToTableBottom];
            NSLog(@"%@",NSStringFromCGRect(_tableView.frame));
    }
}

#pragma mark - 查询结果控制器代理方法
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    // 刷新表格
    [_tableView reloadData];
    
    [self scrollToTableBottom];
}

-(void)keyboardChangeFrame:(NSNotification *)notification
{
//    NSLog(@"%@", notification.userInfo);
    
    // 根据跟踪发现，使用userInfo的UIKeyboardFrameEndUserInfoKey数据可以判断键盘的大小和目标位置
    
    // 1. 获取键盘的目标区域
    NSDictionary *info = notification.userInfo;
    CGRect rect = [info[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat duration = [info[UIKeyboardAnimationDurationUserInfoKey]floatValue];
    
    // 3. 根据rect的orgion.y可以判断键盘是开启还是关闭
    // 3.1 键盘关闭的
    if (rect.origin.y == [UIScreen mainScreen].bounds.size.height) {
        _bottomConstant.constant = 0;
       
    }else{ //3.2 键盘开启的的
        CGFloat kbHeight = rect.size.height;
        _bottomConstant.constant = kbHeight;
    }
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
    [self scrollToTableBottom];
}

#pragma mark - UITextField代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    // 1. 取出文本并截断空白字符串
    NSString *str = [textField.text trimString];
    
    // 2. 实例化XMPPMessage，以便发送
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:_bareJidStr]];
    [message addBody:str];
    
    [[APP_DELEGATE xmppStream] sendElement:message];
    
    textField.text = nil;
    
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - 表格操作方法
#pragma mark 滚动到表格的末尾
-(void)scrollToTableBottom
{
    // 要选中滚动到最末一条记录
    // 1. 知道所有的记录行数
    id <NSFetchedResultsSectionInfo> info = _fetchedResultsController.sections[0];
    NSInteger count = [info numberOfObjects];
    if (count <= 0) {
        return;
    }
    
    // 2. 根据行数实例化indexpath
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(count-1) inSection:0];
    // 3. 选中并滚动到末尾
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
    
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> info = _fetchedResultsController.sections[section];
    return [info numberOfObjects];
}

#pragma mark 每当有一个cell进入视野范围内就会调用，返回当前这行显示的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0.用static修饰的局部变量，只会初始化一次
    static NSString *FromID = @"ChatFromCell";
    static NSString *ToID = @"ChatToCell";
    
    XMPPMessageArchiving_Message_CoreDataObject *message = [_fetchedResultsController objectAtIndexPath:indexPath];
    
    ChatMessageCell *cell = nil;
    
    if (message.isOutgoing) {
        cell = [tableView dequeueReusableCellWithIdentifier:FromID];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:ToID];
    }
    
    // 设置单元格
    
    [cell setMessage:message.body isOutgoing:message.isOutgoing];

    if (message.isOutgoing) {
        cell.headImageView.image = _bareImage;
    }else{
        cell.headImageView.image = _myImage;
    }
    
    return cell;
}

#pragma mark 表格行高

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 提示，在此不能直接调用表格行控件的高度，否则会死循环
    // 1. 取出显示行的文本
    XMPPMessageArchiving_Message_CoreDataObject *message = [_fetchedResultsController objectAtIndexPath:indexPath];
    NSString *str = message.body;
    
    // 2. 计算文本的占用空间
    CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(180, 10000.0)];
    if (size.height + 50.0 > 80.0) {
        return size.height + 50;
    }
    return 80;
}

#pragma mark - UIImagePicker代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // 1. 获取选择的图像
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
     // 2. 关闭照片选择器
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - Actions
#pragma mark 点击添加照片按钮
- (IBAction)clickAddPhoto
{
    // 如何判断摄像头可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"摄像头不可用");
    }
    
    
}
@end
